package com.stark.commons.spring.core.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

import lombok.extern.slf4j.Slf4j;

/**
 * 作业监控切面。
 * <p>监控所有 {@link org.springframework.scheduling.annotation.Scheduled @Scheduled} 注解的方法，
 * 在作业开始执行、结束执行时打印状态日志（包含执行时间，单位秒）。
 * @author Ben
 * @since 1.0.0
 * @version 1.0.0
 */
@Aspect
@Slf4j
public class JobMonitor {
	
	@Around("@annotation(org.springframework.scheduling.annotation.Scheduled)")
	public Object monitor(ProceedingJoinPoint joinPoint) throws Throwable {
		String targetClass = joinPoint.getTarget().getClass().toString().substring("class ".length());
		log.info("{} 作业开始执行...", targetClass);
		long startTime = System.currentTimeMillis();
		
		Object result = null;
		try {
			result = joinPoint.proceed();
		} finally {
			long endTime = System.currentTimeMillis();
			String consume = String.format("%.2f", 1.0 * (endTime - startTime) / 1000) + "秒。";
			log.info("{} 作业结束，耗时 {}", targetClass, consume);
		}
		return result;
	}
	
}
